import {Matrix} from "./matrix";
import {Fence} from "./fence";

class FenceGroup {

    //沟通类

    spu
    skuList
    fences = []

    constructor(spu) {
        this.spu = spu
        this.skuList = spu.sku_list
    }

    getDefaultSku() {
        const defaultSkuId = this.spu.default_sku_id
        if (!defaultSkuId) {
            return   //return undefined
        }
        return this.skuList.find(s => s.id === defaultSkuId)
    }

    setCellStatusById(cellId, status) {
        this.eachCell(cell => {
            if (cell.id === cellId) {
                cell.status = status
            }
        })
    }

    setCellStatusByXY(x, y, status) {
        this.fences[x].cells[y].status = status
    }

    /*initFences1() {
        const matrix = this._createMatrix(this.skuList)
        const fences = []
        let currentJ = -1;
        // 针对每一个元素进行处理，没有把这种处理细节进一步封装，导致后续代码复杂(伪面向对象)
        matrix.each((element, i, j) => {
            // 开启一个新列，需要创建一个新的Fence
            if (currentJ !== j) {
                currentJ = j
                fences[j] = this._createFence()
            }
            fences[j].pushValueTitle(element.value)
        })
    }*/

    initFences() {
        const matrix = this._createMatrix(this.skuList)
        const fences = []
        const AT = matrix.transpose()
        // 保证了很好的封装性
        // 该方法只负责对一行处理，或者是把二维数组拆成一维数组，真正的元素处理交给了Fence类---->封装了元素处理的细节(面向对象编程)
        AT.forEach(r => {
            const fence = new Fence(r)
            fence.init()
            if (this._hasSketchFence() && this._isSketchFence(fence.id)) {
                fence.setFenceSketch(this.skuList)
            }
            fences.push(fence)
        })
        this.fences = fences
    }

    _hasSketchFence() { // 判断spu是否 存在 可视fence  //若存在则进一步判断哪个fence是可视fence
        return this.spu.sketch_spec_id ? true : false
    }

    _isSketchFence(fenceId) { // 判断某个fence是不是可视fence
        return this.spu.sketch_spec_id === fenceId ? true : false
    }

    eachCell(cb) {
        for (let i = 0; i < this.fences.length; i++) {
            for (let j = 0; j < this.fences[i].cells.length; j++) {
                const cell = this.fences[i].cells[j]
                cb(cell, i, j)
            }
        }
    }

    /*_createFence() {
        const fence = new Fence()
        // fence.pushValueTitle(element.value)
        return fence
    }*/

    _createMatrix(skuList) {
        const m = []
        skuList.forEach(sku => {
            m.push(sku.specs)
        })
        return new Matrix(m)
    }

}

export {
    FenceGroup
}